package com.xs.micro.tool.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xs.micro.tool.domain.pojo.em.QueryEnterpriseInfoType;
import com.xs.micro.tool.domain.pojo.vo.EnterpriseInfoResultVO;
import com.xs.micro.tool.domain.pojo.vo.QueryEnterpriseInfoParamVO;
import com.xs.micro.tool.service.BaseQueryDataService;
import okhttp3.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

@Service
public class QueryDataBeiJingServiceImpl extends BaseQueryDataService {

    private static final String POST_URL = "http://creditbj.jxj.beijing.gov.cn/credit-portal/api/extend/list/legal";
    private static final List<Integer> INDEX_LIST = Lists.newArrayList(0, 1, 2);
    private static final String RESULT_TAG = "table.table td";
    private static final int PAGE_SIZE = 20;

    @Override
    public QueryEnterpriseInfoType type() {
        return QueryEnterpriseInfoType.CREDIT_BEI_JING;
    }

    @Override
    public List<EnterpriseInfoResultVO> query(QueryEnterpriseInfoParamVO queryParam) throws Exception {

        Map<String, String> header = Maps.newHashMap();
        header.put("Host", POST_URL);
        header.put("Origin", POST_URL);
        header.put("Referer", POST_URL);
        OkHttpClient client = createOkHttpClient(header);

        List<EnterpriseInfoResultVO> list = Lists.newArrayList();

        // 处理中文
        String keyword = encode(queryParam.getKeyword());
        int maxCount = queryParam.getMaxCount();
        int maxPage = maxCount / PAGE_SIZE;
        for (int p = 0; p < maxPage; p++) {
            RequestBody body = RequestBody.create("{\"listSql\":\"\",\"linesPerPage\":10,\"currentPage\":" + (p + 1) + ",\"condition\":{\"keyWord\":\"" + queryParam.getKeyword() + "\"}}", MediaType.parse("application/json"));
            Request request = new Request.Builder().url(POST_URL).post(body).build();
            Response response = client.newCall(request).execute();

            Assert.isTrue(response.isSuccessful(), "查询异常." + response.message());

            String json = response.body().toString();
            JSONObject jsonObject = JSON.parseObject(json);

        }
        return list;
    }
}
